package com.cash.loan.modular.cash.service.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import com.cash.loan.core.util.FilePathUtil;
import com.cash.loan.modular.cash.dao.CashUserLoginMapper;
import com.cash.loan.modular.cash.dao.CashUserMapper;
import com.cash.loan.modular.cash.dao.ProductVisitMapper;
import com.cash.loan.modular.cash.result.PageResult;
import com.cash.loan.modular.cash.service.CashUserService;
import com.cash.loan.modular.cash.transfer.UserExcelVo;
import com.cash.loan.modular.cash.transfer.UserVo;
import com.cash.loan.modular.cash.util.PageBeanUtil;
import com.github.pagehelper.PageHelper;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 用户管理
 *
 * @author Administrator
 * @Date 2018-07-13 8:49
 */
@Service
public class CashUserServiceImpl implements CashUserService {

    @Autowired
    private CashUserMapper userMapper;

    @Autowired
    private ProductVisitMapper productVisitMapper;

    @Autowired
    private CashUserLoginMapper cashUserLoginMapper;

    @Override
    public PageResult<UserVo> getUserList(Integer currentPage, Integer pageSize, String keyword, Date sDate,Date eDate) {
        PageHelper.startPage(currentPage,pageSize);

        List<UserVo> userList = userMapper.getUserList(keyword,sDate,eDate);

        userList.stream().forEach(userVo -> {
            if(StringUtils.isBlank(userVo.getRealName())) {
                userVo.setRealName("");
            }
            if(StringUtils.isBlank(userVo.getRegFrom())) {
                userVo.setRegFrom("");
            }
        });

        PageResult<UserVo> pageResult = PageBeanUtil.toPageResult(userList);

        return pageResult;
    }

    @Override
    public String getUserInfoToExcel(Date sDate,Date eDate) {
        List<UserExcelVo> userExcelVoList = userMapper.getUserByDate(sDate,eDate);
        Map<String,Object> map = new HashMap<>(8);
        List<Map<String,String>> mapList = new ArrayList<>();
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        File targetFile = new File(getTempPath()+"template.xlsx");
        if(!targetFile.exists()) {
            InputStream inputStream = getClass().getClassLoader().getResourceAsStream("用户信息.xlsx");
            try {
                FileUtils.copyInputStreamToFile(inputStream, targetFile);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        TemplateExportParams params = new TemplateExportParams(
                getTempPath()+"template.xlsx");
        userExcelVoList.stream().forEach(
                userExcelVo -> {
                    Map<String,String> userMap = new HashMap<>();
                    userMap.put("id",""+userExcelVo.getId());
                    userMap.put("regDate",df.format(userExcelVo.getRegDate()));
                    userMap.put("phone",userExcelVo.getPhone());
                    if(StringUtils.isNoneBlank(userExcelVo.getRegFrom())) {
                        userMap.put("regFrom",userExcelVo.getRegFrom());
                    } else {
                        userMap.put("regFrom",null);
                    }
                    mapList.add(userMap);
                }
        );
        map.put("mapList",mapList);
        Workbook workbook = ExcelExportUtil.exportExcel(params, map);
        FileOutputStream fos = null;
        String filePath = getTempPath() + "用户信息.xlsx";
        try {
            fos = new FileOutputStream(filePath);
            workbook.write(fos);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return FilePathUtil.normalizePath(filePath);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public Boolean deleteUser(Integer id) {
        //删除各类绑定关系
        productVisitMapper.deleteByVisitId(Long.valueOf(id));
        //删除账号表中的数据
        Long accountId = userMapper.getAccountIdById(Long.valueOf(id));
        cashUserLoginMapper.deleteById(accountId);
        //删除用户表中的数据
        userMapper.deleteById(Long.valueOf(id));
        return true;
    }

    /**
     * 得到临时文件夹
     * @return
     */
    public String getTempPath() {
        return System.getProperty("java.io.tmpdir");
    }
}
